package neatlogic.module.change.api;

import neatlogic.framework.asynchronization.threadlocal.UserContext;
import neatlogic.framework.auth.core.AuthAction;
import neatlogic.framework.change.constvalue.*;
import neatlogic.framework.change.dto.*;
import neatlogic.framework.common.constvalue.ApiParamType;
import neatlogic.framework.process.auth.PROCESS_BASE;
import neatlogic.framework.process.dao.mapper.ProcessTaskMapper;
import neatlogic.framework.process.dto.ProcessTaskStepVo;
import neatlogic.framework.process.exception.process.ProcessStepUtilHandlerNotFoundException;
import neatlogic.framework.process.stephandler.core.IProcessStepHandlerUtil;
import neatlogic.framework.process.stephandler.core.IProcessStepInternalHandler;
import neatlogic.framework.process.stephandler.core.ProcessStepInternalHandlerFactory;
import neatlogic.framework.restful.annotation.Description;
import neatlogic.framework.restful.annotation.Input;
import neatlogic.framework.restful.annotation.OperationType;
import neatlogic.framework.restful.annotation.Param;
import neatlogic.framework.restful.constvalue.OperationTypeEnum;
import neatlogic.framework.restful.core.privateapi.PrivateApiComponentBase;
import neatlogic.module.change.dao.mapper.ChangeMapper;
import neatlogic.framework.change.exception.ChangeHandleHasNotStartedException;
import neatlogic.framework.change.exception.ChangeNoPermissionException;
import neatlogic.framework.change.exception.ChangeStepNotFoundException;
import neatlogic.module.change.service.ChangeService;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
@AuthAction(action = PROCESS_BASE.class)
@OperationType(type = OperationTypeEnum.OPERATE)
public class ChangeStepAbortApi extends PrivateApiComponentBase {

    @Autowired
    private ChangeMapper changeMapper;

    @Autowired
    private ChangeService changeService;

    @Autowired
    private ProcessTaskMapper processTaskMapper;

    @Autowired
    private IProcessStepHandlerUtil IProcessStepHandlerUtil;

    @Override
    public String getToken() {
        return "change/step/abort";
    }

    @Override
    public String getName() {
        return "取消变更步骤";
    }

    @Override
    public String getConfig() {
        return null;
    }

    @Input({
            @Param(name = "changeStepId", type = ApiParamType.LONG, isRequired = true, desc = "变更步骤id"),
            @Param(name = "changeAction", type = ApiParamType.ENUM, rule = "pausechange,abortchangestep", desc = "暂停变更或取消变更步骤"),//TODO linbq isRequired = true,
            @Param(name = "content", type = ApiParamType.STRING, isRequired = true, minLength = 1, desc = "描述"),
            @Param(name = "source", type = ApiParamType.STRING, defaultValue = "pc", desc = "来源")
    })
    @Description(desc = "取消变更步骤")
    @Override
    public Object myDoService(JSONObject jsonObj) throws Exception {
        Long changeStepId = jsonObj.getLong("changeStepId");
        ChangeStepVo changeStep = changeMapper.getChangeStepById(changeStepId);
        if (changeStep == null) {
            throw new ChangeStepNotFoundException(changeStepId);
        }
        /** 获取当前变更锁 **/
        changeMapper.getChangeLockById(changeStep.getChangeId());
        ChangeVo changeVo = changeMapper.getChangeById(changeStep.getChangeId());
        changeService.getChangeStepDetail(changeStep);
        if (!changeService.isAbortableChangeStep(changeVo, changeStep)) {
            throw new ChangeNoPermissionException(ChangeOperationType.ABORTCHANGESTEP.getText());
        }
        /** 取消变更步骤时，将变更步骤状态设置为“已取消” **/
        changeStep.setStatus(ChangeStatus.ABORTED.getValue());
        changeMapper.updateChangeStepStatus(changeStep);

        /** 取消变更步骤时，触发更新processtask_step_worker和processtask_step_user数据 **/
        ProcessTaskStepChangeVo processTaskStepChangeVo = changeMapper.getProcessTaskStepChangeHandleByChangeId(changeStep.getChangeId());
        if (processTaskStepChangeVo == null) {
            throw new ChangeHandleHasNotStartedException();
        }
        IProcessStepInternalHandler processStepUtilHandler = ProcessStepInternalHandlerFactory.getHandler(ChangeProcessStepHandlerType.CHANGEHANDLE.getHandler());
        if (processStepUtilHandler == null) {
            throw new ProcessStepUtilHandlerNotFoundException(ChangeProcessStepHandlerType.CHANGEHANDLE.getHandler());
        }

        /** 生产回复**/
        String content = jsonObj.getString("content");
        ChangeContentVo contentVo = new ChangeContentVo(content);
        changeMapper.replaceChangeContent(contentVo);
        ChangeStepCommentVo comment = new ChangeStepCommentVo();
        comment.setContentHash(contentVo.getHash());
        comment.setChangeId(changeStep.getChangeId());
        comment.setChangeStepId(changeStepId);
        comment.setFcu(UserContext.get().getUserUuid(true));
        changeMapper.insertChangeStepComment(comment);

        String changeAction = jsonObj.getString("changeAction");
        if (ChangeOperationType.PAUSECHANGE.getValue().equals(changeAction)) {
            /** 暂停变更时，将变更状态设置为“已取消”，变更步骤状态不变 **/
            changeVo.setStatus(ChangeStatus.PAUSED.getValue());
            changeMapper.updateChangeStatus(changeVo);
            changeMapper.insertChangeStepPauseOperate(new ChangeStepPauseOperateVo(changeStep.getChangeId(), changeStep.getId(), UserContext.get().getUserId(true)));
            ProcessTaskStepVo currentProcessTaskStepVo = processTaskMapper.getProcessTaskStepBaseInfoById(processTaskStepChangeVo.getProcessTaskStepId());
            /** 变更暂停提醒 **/
            IProcessStepHandlerUtil.saveStepRemind(currentProcessTaskStepVo, currentProcessTaskStepVo.getId(), jsonObj.getString("content"), ChangeRemindType.PAUSECHANGE);

            processStepUtilHandler.updateProcessTaskStepUserAndWorker(processTaskStepChangeVo.getProcessTaskId(), processTaskStepChangeVo.getProcessTaskStepId());

            currentProcessTaskStepVo.getParamObj().putAll(jsonObj);
            IProcessStepHandlerUtil.audit(currentProcessTaskStepVo, ChangeAuditType.PAUSECHANGE);
            IProcessStepHandlerUtil.notify(currentProcessTaskStepVo, ChangeTriggerType.PAUSECHANGE);
            IProcessStepHandlerUtil.action(currentProcessTaskStepVo, ChangeTriggerType.PAUSECHANGE);
        } else {
            /** 取消当前变更步骤时，触发激活其他变更步骤 **/
            changeService.activeChangeStep(changeStep.getChangeId());

            processStepUtilHandler.updateProcessTaskStepUserAndWorker(processTaskStepChangeVo.getProcessTaskId(), processTaskStepChangeVo.getProcessTaskStepId());
            /** 生成活动 **/
            ProcessTaskStepVo currentProcessTaskStepVo = new ProcessTaskStepVo();
            currentProcessTaskStepVo.setProcessTaskId(processTaskStepChangeVo.getProcessTaskId());
            currentProcessTaskStepVo.setId(processTaskStepChangeVo.getProcessTaskStepId());
            currentProcessTaskStepVo.getParamObj().put("changeStepName", changeStep.getName());
            currentProcessTaskStepVo.getParamObj().putAll(jsonObj);
            IProcessStepHandlerUtil.audit(currentProcessTaskStepVo, ChangeAuditType.ABORTCHANGESTEP);
            IProcessStepHandlerUtil.notify(currentProcessTaskStepVo, ChangeTriggerType.ABORTCHANGESTEP);
            IProcessStepHandlerUtil.action(currentProcessTaskStepVo, ChangeTriggerType.ABORTCHANGESTEP);

            /** 判断所有变更步骤是否都完成了 **/
            List<ChangeStepVo> changeStepList = changeMapper.getChangeStepListByChangeId(changeStep.getChangeId());
            if(CollectionUtils.isNotEmpty(changeStepList)){
                for (ChangeStepVo changeStepVo : changeStepList) {
                    if (!changeStepVo.getStatus().equals(ChangeStatus.SUCCEED.getValue()) && !changeStepVo.getStatus().equals(ChangeStatus.ABORTED.getValue())) {
                        return null;
                    }
                }
                IProcessStepHandlerUtil.notify(currentProcessTaskStepVo, ChangeTriggerType.COMPLETEALLCHANGESTEP);
                IProcessStepHandlerUtil.action(currentProcessTaskStepVo, ChangeTriggerType.COMPLETEALLCHANGESTEP);
            }
        }
        return null;
    }

}
